<template>
  <div v-loading="loading" class="app-container">
    <el-form ref="form" :model="form" :rules="rules" label-width="80px" class="dataForm">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            v-hasPermi="['system:dict:edit']"
            type="primary"
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
          >{{ $t("新增") }}</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            v-hasPermi="['system:dict:export']"
            type="warning"
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
          >{{ $t("导出") }}</el-button>
        </el-col>
      </el-row>
      <el-table
        :data="form.dataList"
        border
        class="formTable"
        @selection-change="handleSelectionChange"
      >
        <el-table-column width="40" type="selection" align="center" />
        <el-table-column width="120" :label="$t('排序')" align="center">
          <template slot-scope="scope">
            <el-form-item :prop="'dataList.' + scope.$index + '.dictSort'" :rules="rules.dictSort">
              <el-input-number v-model="scope.row.dictSort" controls-position="right" :min="0" />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column :label="$t('字典标签')">
          <template slot-scope="scope">
            <el-form-item
              :prop="'dataList.' + scope.$index + '.dictLabel'"
              :rules="rules.dictLabel"
            >
              <el-input v-model="scope.row.dictLabel" />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column :label="$t('字典键值')">
          <template slot-scope="scope">
            <el-form-item
              :prop="'dataList.' + scope.$index + '.dictValue'"
              :rules="rules.dictValue"
            >
              <el-input v-model="scope.row.dictValue" />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column width="80" :label="$t('状态')" align="center">
          <template slot-scope="scope">
            <el-switch
              :v-model="scope.row.status"
              :value="scope.row.status"
              active-value="0"
              inactive-value="1"
              @change="handleStatusChange(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column>
          <span slot="header">
            {{ $t('关联字典') }}
            <el-tooltip :content="$t('关联的二级字典')" placement="top">
              <i class="el-icon-question" />
            </el-tooltip>
          </span>
          <template slot-scope="scope">
            <el-select v-model="scope.row.childDict" clearable filterable :placeholder="$t('请选择')">
              <el-option
                v-for="dict in dictOptions"
                :key="dict.dictType"
                :label="$t(dict.dictName)"
                :value="dict.dictType"
              >
                <span style="float: left">{{ $t(dict.dictName) }}</span>
                <span style="float: right; color: #8492a6; font-size: 13px">{{ dict.dictType }}</span>
              </el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column :label="$t('备注')" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <el-input v-model="scope.row.remark" :maxlength="500" show-word-limit />
          </template>
        </el-table-column>

        <el-table-column
          width="50"
          :label="$t('操作')"
          align="center"
          class-name="small-padding fixed-width"
        >
          <template slot-scope="scope">
            <el-button
              v-hasPermi="['system:dict:remove']"
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDel(scope.$index, scope.row)"
            />
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </el-form>
    <div
      slot="footer"
      class="dialog-footer"
      style="text-align: right;width: 100%;"
    >
      <el-button @click="cancel">{{ $t("取消") }}</el-button>
      <el-button v-hasPermi="['system:dict:edit']" type="primary" @click="submitForm()">{{ $t("确定") }}</el-button>
    </div>
  </div>
</template>

<script>
// eslint-disable-next-line no-unused-vars
import {
  listData,
  delData,
  addData,
  updateData,
  exportData
} from '@/api/system/dict/data'
import { optionselect as getDictOptionselect } from '@/api/system/dict/type'
import { listType, getType } from '@/api/system/dict/type'
import elDragDialog from '@/directive/el-drag-dialog'
export default {
  name: 'Data',
  directives: { elDragDialog },
  props: {
    dictIdChild: {
      type: String,
      default: null
    }
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,

      // 状态数据字典
      statusOptions: [],
      // 类型数据字典
      typeOptions: [],
      // 字典信息
      dictOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        dictName: undefined,
        dictType: undefined,
        status: undefined
      },
      // 表单参数
      form: {
        // 字典ID
        id: undefined,
        // 字典类型
        dictType: undefined,
        // 字典名称
        dictName: undefined,
        // 字典表格数据
        dataList: []
      },
      // 表单校验
      rules: {
        dictLabel: [
          { required: true, message: this.$t('必填信息'), trigger: 'blur' }
        ],
        dictValue: [
          { required: true, message: this.$t('必填信息'), trigger: 'blur' }
        ],
        dictSort: [
          { required: true, message: this.$t('必填信息'), trigger: 'blur' }
        ]
      }
    }
  },
  watch: {
    dictIdChild: {
      immediate: true, // 很重要！！！
      handler(val) {
        this.dictIdChild = !val ? {} : val
        const dictId = this.dictIdChild
        this.getType(dictId)
      }
    }
  },

  created() {
    this.getTypeList()
    this.getDicts('sys_normal_disable').then((response) => {
      this.statusOptions = response.data
    })
    /** 查询字典下拉列表 */
    getDictOptionselect().then((response) => {
      this.dictOptions = response.data
    })
  },
  methods: {
    /** 查询字典类型详细 */
    getType(dictId) {
      getType(dictId).then((response) => {
        this.queryParams.dictType = response.data.dictType
        this.form.id = response.data.id
        this.form.dictName = response.data.dictName
        this.form.dictType = response.data.dictType
        this.getList()
      })
    },
    /** 查询字典类型列表 */
    getTypeList() {
      listType().then((response) => {
        this.typeOptions = response.rows
      })
    },
    /** 查询字典数据列表 */
    getList() {
      this.loading = true
      listData(this.queryParams).then((response) => {
        this.form.dataList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 字典状态修改 0启用 1停用
    handleStatusChange(row) {
      if (row.id) {
        row.status = row.status === '0' ? '1' : '0'
        const text = row.status === '0' ? '启用' : '停用'
        this.$confirm(
          this.$t('确认要') + this.$t(text) + this.$t(row.dictLabel) + '?',
          this.$t('警告'),
          {
            confirmButtonText: this.$t('确定'),
            cancelButtonText: this.$t('取消'),
            type: 'warning'
          })
          .then(function() {
            return updateData(row)
          })
          .then(() => {
            this.msgSuccess(text + '成功')
          })
          .catch(function() {
            row.status = row.status === '0' ? '1' : '0'
          })
      } else {
        row.status = '1'
      }
    },

    /** 删除按钮操作 */
    handleDel(index, row) {
      console.log(index, row)
      // eslint-disable-next-line eqeqeq
      if (row.id !== null && row.id !== undefined && row.id !== '') {
        this.$confirm(this.$t('是否确认删除?'), this.$t('警告'), {
          confirmButtonText: this.$t('确定'),
          cancelButtonText: this.$t('取消'),
          type: 'warning'
        })
          .then(function() {
            return delData(row.id)
          })
          .then(() => {
            this.form.dataList.splice(index, 1)
            this.msgSuccess(this.$t('删除成功'))
          })
          .catch(function() {})
        // eslint-disable-next-line eqeqeq
      } else {
        this.form.dataList.splice(index, 1)
      }
    },
    // 数据状态字典翻译
    statusFormat(row, column) {
      console.log(column)
      return this.selectDictLabel(this.statusOptions, row.status)
    },
    // 取消按钮
    cancel() {
      this.$parent.$parent.dictOpen = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        // 字典ID
        id: undefined,
        // 字典类型
        dictType: undefined,
        // 字典名称
        dictName: undefined,
        // 字典表格数据
        dataList: []
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    /** 新增按钮操作 */
    handleAdd() {
      const row = {
        dictCode: '',
        dictLabel: '',
        dictValue: '',
        dictSort: this.form.dataList.length + 1,
        status: '0',
        remark: ''
      }
      this.form.dataList.push(row)
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.dictCode)
      this.multiple = !selection.length
    },
    // /** 修改按钮操作 */
    // handleUpdate(row) {
    //   this.reset()
    //   const dictCode = row.dictCode || this.ids
    //   getData(dictCode).then(response => {
    //     this.form = response.data
    //     this.open = true
    //     this.title = '修改字典数据'
    //   })
    // },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.loading = true
          if (this.form.dictCode !== undefined) {
            updateData(this.form).then((response) => {
              if (response.code === 200) {
                this.msgSuccess(this.$t('修改成功'))
                this.open = false
                this.getList()
              } else {
                this.msgError(response.msg)
                this.loading = false
              }
            }).catch(() => {
              this.loading = false
            })
          } else {
            addData(this.form).then((response) => {
              if (response.code === 200) {
                this.msgSuccess(this.$t('新增成功'))
                this.open = false
                this.getList()
              } else {
                this.msgError(response.msg)
                this.loading = false
              }
            }).catch(() => {
              this.loading = false
            })
          }
        } else {
          this.locationError(document)
        }
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams
      this.$confirm(this.$t('是否确认导出?'), this.$t('警告'), {
        confirmButtonText: this.$t('确定'),
        cancelButtonText: this.$t('取消'),
        type: 'warning'
      })
        .then(function() {
          return exportData(queryParams)
        })
        .then((response) => {
          this.download(response.msg)
        })
        .catch(function() {})
    }
  }
}
</script>
